package com.cos.shop.dao.impl;

import com.cos.shop.dao.OrderDao;
import com.cos.shop.entity.Orders;
import com.cos.shop.util.DBUtils;
import com.cos.shop.vo.OrderDetailVo;
import com.cos.shop.vo.OrderListVo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: COS
 * @time: 2023/5/12 9:23
 * @description:
 */
public class OrderDaoImpl implements OrderDao {
    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    @Override
    public Orders getOrrderByOid(String oid) throws SQLException {
        String sql = "select " +
                "  `o_id` 'oid'," +
                "  o.`u_id` 'uid'," +
                "  o.`a_id` 'aid'," +
                "  `o_count` 'ocount'," +
                "  `o_time` 'otime'," +
                "  `o_state` 'ostate'" +
                " from orders o where o_id = ?";
        return qr.query(sql,
                new BeanHandler<>(Orders.class),oid);
    }

    @Override
    public int changeStatus(int state, String oid) throws SQLException {
        String sql ="update orders set o_state = ? where o_id = ?";
        return qr.update(sql,state,oid);
    }

    @Override
    public OrderDetailVo getOrderDetail(String oid) throws SQLException {
        String sql = "select " +
                "  `o_id` 'oid'," +
                "  o.`u_id` 'uid'," +
                "  o.`a_id` 'aid'," +
                "  `o_count` 'ocount'," +
                "  `o_time` 'otime'," +
                "  `o_state` 'ostate' ," +
                "  a_detail 'adetail'," +
                "  a_name 'aname'," +
                "  a_phone 'aphone'" +
                " from orders o inner join address a " +
                " on o.a_id=a.a_id " +
                " where o.o_id=?";
        return qr.query(sql,new BeanHandler<>(OrderDetailVo.class),oid);
    }

    @Override
    public List<OrderListVo> getOrderList(int uid) throws SQLException {
        String sql = "select " +
                "  `o_id` 'oid'," +
                "  o.`u_id` 'uid'," +
                "  o.`a_id` 'aid'," +
                "  `o_count` 'ocount'," +
                "  `o_time` 'otime'," +
                "  `o_state` 'ostate' ," +
                "  a_detail 'adetail'" +
                "from orders o inner join address a " +
                "on o.a_id=a.a_id " +
                "where o.u_id=?";
        return qr.query(sql, new BeanListHandler<>(OrderListVo.class),uid);
    }

    @Override
    public int addOrder(Orders o) throws SQLException {
        String sql = "insert into orders values (?,?,?,?,?,?)";
        return qr.update(DBUtils.getConnection(),sql,
                o.getOid(),o.getUid(),o.getAid(),o.getOcount(),o.getOtime(),o.getOstate());
    }
}
